package cc.linker.steplink.crm.merchanth5.service;


import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.response.GlobalException;
import com.mongodb.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class MallBoomService {

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private MallDao mallDao;

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.getwxlist}")
    private String doAddbAccountUrl;

    public Integer getJoinMoney(String orgId) {
        return mallBoomDao.getJoinMoney(orgId);
    }

    public void setInit(Map<String, Object> param){
        mallBoomDao.setInit(param);
    }

    public Map<String,Object> getCustomerInfoByCustomerId(String customerId){
        return mallBoomDao.getCustomerInfoByCustomerId(customerId);
    };

    public Integer getJoinMoneyPromoter(String orgId) {
        return mallBoomDao.getJoinMoneyPromoter(orgId);
    }

    public Integer getJoinRebate(String orgId) {
        return mallBoomDao.getJoinRebate(orgId);
    }

    public Integer getSalerCount(Map map) {
        return mallBoomDao.getSalerCount(map);
    }

    public HashMap<String, Object> getSalerOrder(Map map) {
        return mallBoomDao.getSalerOrder(map);
    }

    public HashMap<String, Object> getJoinStatus(Map map) {
        return mallBoomDao.getJoinStatus(map);
    }

    public HashMap<String, Object> getSalerOrderBySn(String orderSn) {
        return mallBoomDao.getSalerOrderBySn(orderSn);
    }

    public Integer addSalerOrder(Map map) {
        return mallBoomDao.addSalerOrder(map);
    }

    public Boolean addSaler(Map map) {
        return mallBoomDao.addSaler(map) == 1;
    }

    public Boolean doneSalerOrder(Map map) {
        return mallBoomDao.doneSalerOrder(map) == 1;
    }

    public Boolean editSalerOrder(Map map) {
        return mallBoomDao.editSalerOrder(map) == 1;
    }

    public Boolean addAccountTrade(Map map) {
        //如果是推荐人，账单明细中需要维护实时余额
        String salerId = (String) map.get("salerId");
        if (!StringUtils.isEmpty(salerId)) {
            //更新账户余额
//            mallDao.updateAccountBalance(map);
            // 存到表，等下次产生实物交易的时候一并给
            // 收款人salerId金额tradeSum付款人payUser
            mallBoomDao.addRebateTrade(map);
            Long useableMoneyBelong = mallDao.getUseableMoneyByUid(salerId) + Long.valueOf(map.get("tradeSum").toString());
            map.put("reciveAccountBalance", useableMoneyBelong);
        } else {
            map.put("reciveAccountBalance", "0");
        }
        return mallBoomDao.addAccountTrade(map) == 1;
    }

    public List<Map<String, String>> getSonBoomList(String pcustomerId) {
        return mallBoomDao.getSonBoomList(pcustomerId);
    }

//    public Boolean saveBusinessImg(Map map){
//        return mallBoomDao.saveBusinessImg(map)==1;
//    }

    public Boolean savephone(Map<String, String> params) {
        try{
            //新增联盟商家时获取默认客服，若不会存在管理中心会自动创建
            String uid = params.get("casUserId");
            Map<String, Object> pushData = new HashMap<>();
            pushData.put("uid",uid);
            httpService.doGet(doAddbAccountUrl + "?action=getbCustomerInfo", pushData);
        }catch(Exception e){
            //do nothing
        }
        return mallBoomDao.updateSalerInfo(params) == 1;
    }

    public HashMap<String, Object> getMyBoom(String customerId) {
        HashMap<String, Object> ret = mallBoomDao.getMyBoom(customerId);
        ret.put("customerFreeze", NumberUtils.fenToYuan(Long.valueOf(ret.get("customerFreeze").toString())));
        ret.put("amount", NumberUtils.fenToYuan(Long.valueOf(ret.get("amount").toString())));
        return ret;
    }

    ;

    public HashMap<String, String> getSalerAccount(String customerId) throws IOException, URISyntaxException {
        HashMap<String, String> salerAccount = mallBoomDao.getSalerAccount(customerId);
        if(StringUtils.isEmpty(salerAccount.get("userName")) && StringUtils.isEmpty(salerAccount.get("password"))) {
            Map<String, Object> customerInfo = getCustomerInfoByCustomerId(customerId);
            if (null == customerInfo) {
                throw GlobalException.build("用户信息不存在");
            }
            String orgId = customerInfo.get("orgId").toString();
            String phone = customerInfo.get("bindPhone").toString();
            String username = customerInfo.get("customerName").toString();
            if(StringUtils.isEmpty(username)){
                username = "手机尾号"+phone.substring(phone.length()-4)+"用户";
            }
            Map<String, String> salerParam = new HashMap<>();
            salerParam.put("orgId", orgId);
            salerParam.put("customerId", customerId);

            Integer salerCount = getSalerCount(salerParam);//判断该用户是不是小b
            if (salerCount > 0) {
                //生成小b用于登录cas的账号
                String casUserName = "mbl" + phone + orgId;
                String casPassword = getRandom(6);
                Map<String, Object> pushData = new HashMap<>();
                pushData.put("orgcode", orgId);
                pushData.put("account", casUserName);
                pushData.put("username", username);
                pushData.put("pwd", DigestUtils.md5DigestAsHex(casPassword.getBytes()));
                String postres = httpService.doGet(doAddbAccountUrl + "?action=doAddbAccount", pushData);
                if (null == postres) {
                    throw GlobalException.build("验证失败，请重试");
                }
                Map res = (Map) JSON.parse(postres);
                if ((Integer) res.get("RetCode") != 0) {
                    switch ((Integer) res.get("RetCode")) {
                        case 3:
                            throw GlobalException.build("你已是麦爆啦店主，请勿重复开通");
                        case 5:
                            throw GlobalException.build("用户达到上限，请联系管理员");
                        default:
                            break;
                    }
                    throw GlobalException.build("系统繁忙，请稍后再试");
                }
                Map<String, String> params = new HashMap<>();
                params.put("casUserId", res.get("UserID").toString());
                params.put("casUserName", casUserName);
                params.put("casPassword", casPassword);
                params.put("phone", phone);
                params.put("customerId", customerId);
                savephone(params);
                salerAccount.put("userName",casUserName);
                salerAccount.put("password",casPassword);
            }
        }
        return salerAccount;
    }


    public String getRandom(int length){
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val.append(random.nextInt(10));
        }
        return val.toString();
    }

    public List<Map<String, Object>> getAllMallBoomGoods(Map sqlparam) {
        return mallBoomDao.getAllMallBoomGoods(sqlparam);
    }

    public int getGoodsCount(Map sqlparam) {
        return mallBoomDao.getGoodsCount(sqlparam);
    }

//    public List<Map<String,Object>> getAllMallBoomGoods(String orgId){
//        return mallBoomDao.getAllMallBoomGoods(orgId);
//    }

    public String getUserIdBySalerId(String SalerId) {
        return mallBoomDao.getUserIdBySalerId(SalerId);
    }

    public int mobileCount(String phone, String orgId) {
        return mallBoomDao.mobileCount(phone, orgId);
    }

    public Long getSkuMoneyByGoodsId(String goodsId) {
        return mallBoomDao.getSkuMoneyByGoodsId(goodsId);
    }

    public Integer getJoinRebateRf(String orgId) {
        return mallBoomDao.getJoinRebateRf(orgId);
    }

    public Map<String, Integer> getReverseProfitModel(String orgId) {
        return mallBoomDao.getReverseProfitModel(orgId);
    }

    public String findPid(String cid) {
        return mallBoomDao.findPid(cid);
    }

    public boolean isSalerByCid(String cid) {
        return mallBoomDao.isSalerByCid(cid) == 1;
    }

    //获取当前用户推荐关注的子用户
    public List<Map<String, String>> getShareUserList(Map map) {
        return mallBoomDao.getShareUserList(map);
    }

    //获取推广员反润
    public Long getUserContributionMoney(Map map) {
        return mallBoomDao.getUserContributionMoneyZj(map);
//        String ifzj = map.get("ifzj").toString();
//        if("1".equals(ifzj)){
//            return mallBoomDao.getUserContributionMoneyZj(map);
//        }else{
//            return mallBoomDao.getUserContributionMoney(map);
//        }
    }

    //判断当前用户是不是加盟代理
    public Integer getPromoterCount(Map map) {
        return mallBoomDao.getPromoterCount(map);
    }
    //判断当前用户是不是推广员
    public Integer getAgentCount(Map map) {
        return mallBoomDao.getAgentCount(map);
    }

    //用户成为加盟代理
    public Boolean savePromoter(String customerId) {
        return mallBoomDao.savePromoter(customerId) == 1;
    }

    //绑定上下级关系
    public void saveCustomerParent(Map param){
        mallBoomDao.saveCustomerParent(param);
    }

    //检查该用户是否绑定过手机号
    public Boolean checkCustomerPhone(String customerId){
        String phone = mallBoomDao.getCustomerPhone(customerId);
        if(StringUtils.isEmpty(phone)){
            return false;
        }else{
            return true;
        }
    }
    //检查该联盟商家是否绑定过手机号
    public Boolean checkSalerPhone(String customerId){
        String phone = mallBoomDao.checkSalerPhone(customerId);
        if(StringUtils.isEmpty(phone)){
            return false;
        }else{
            return true;
        }
    }

    //将手机号写入customer表
    public void saveCustomerPhone(String customerId,String phoneNum){
        mallBoomDao.saveCustomerPhone(customerId,phoneNum);
    }

    public void openAccount(Map<String, Object> map) {
        mallBoomDao.openAccount(map);
    }

    public String findCustomerName(String customerId) {
        return mallBoomDao.findCustomerName(customerId);
    }

    public Map<String,String> getOrgCutByOrgId(String orgId){
        return mallBoomDao.getOrgCutByOrgId(orgId);
    }

    public String getCustomerIdByEaccount(String eaccount){
        return mallBoomDao.getCustomerIdByEaccount(eaccount);
    }

    public Map<String,Object> getSalerOrderBysn(String orderSn){
        return mallBoomDao.getSalerOrderBysn(orderSn);
    }

    public int delivery(Map<String, Object> params) {
        mallBoomDao.delivery(params);
        int count = mallBoomDao.getNotDeliveryCount(params);
        if (count == 0) {
            mallBoomDao.updateOrderStatus(params);
        }
        return count;
    }

    public Map<String, Object> getMsgInfo(Map<String, Object> params) {
        return mallBoomDao.getMsgInfo(params);
    }

    public Map getOrderInfoById(Long orderId,Integer payMode){
        return mallBoomDao.getOrderInfoById(orderId,payMode);
    }

    /**
     * 更新绑定手机号
     * @param params
     *  参数 bindPhone  customerId
     *
     */
    public void updateBindPhoneByCid(Map<String,Object> params)
    {
        mallBoomDao.updateBindPhoneByCid(params);
    }

    /**
     * 获取绑定手机号
     * @param customerId
     * @return
     */
    public String getBindPhoneByCid(String customerId)
    {
        return mallBoomDao.getBindPhoneByCid(customerId);
    }

    public String getGoodsBelongIdByGoodsId(Integer goodsId) {
        return mallBoomDao.getGoodsBelongIdByGoodsId(goodsId);
    }

    public void resavePromoter(String customerId) {
        mallBoomDao.resavePromoter(customerId);
    }

    public String getAgentCountStatus(String customerId) {
        return mallBoomDao.getAgentCountStatus(customerId);
    }

    public Map<String, Object> getPromoterInfo(Map<String, String> tmpParam) {
       return mallBoomDao.getPromoterInfo(tmpParam);
    }

    public Integer getSalerPromoter(Map<String, String> tmpParam) {
        return mallBoomDao.getSalerPromoter(tmpParam);
    }

    public Integer getStreamByCustomerId(String customerId) {
        return mallBoomDao.getStreamByCustomerId(customerId);
    }

    public List<Map<String,Object>> getGoodsInfoByGoodsIds(List<String> goodsIds){
        return mallBoomDao.getGoodsInfoByGoodsIds(goodsIds);
    }
}
